﻿using ERP.ERPModels.HumanResources.HumanResourceManagement;
using ERP.HumanResources.HumanResourceManagement;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using System.Linq;
using Volo.Abp.Application.Dtos;
using Microsoft.EntityFrameworkCore;
using System.IO;
using System;
using System.Collections.Generic;
using OfficeOpenXml;
using ERP.HumanResources.HumanResourceManagement.Dtos;

namespace ERP.Web.Controllers.HumanResources.HumanResourceManagement
{
    public class JobApplicationController : Controller
    {
        private readonly IRepository<JobApplication, int> _jobApplicationRepository;
        private readonly IJobApplicationService _jobApplicationService;

        public JobApplicationController(IRepository<JobApplication, int> jobApplicationRepository, IJobApplicationService jobApplicationService)
        {
            _jobApplicationRepository = jobApplicationRepository;
            _jobApplicationService = jobApplicationService;
        }

        /// <summary>
        /// 入职申请视图
        /// </summary>
        /// <returns></returns>
        public IActionResult JobIndex()
        {
            return View();
        }
        public IActionResult JobReview()
        {
            return View();
        }

        /// <summary>
        /// 显示入职申请分页列表
        /// </summary>
        /// <param name="param">查询参数</param>
        /// <returns>分页结果</returns>
        [HttpGet]
        public async Task<IActionResult> JobApplicationPageList([FromQuery]JobApplicationPageListDTO param)
        {
            // 1. 构建查询
            var query = await _jobApplicationRepository
                .GetQueryableAsync();

            // 2. 应用筛选条件
            if (!string.IsNullOrEmpty(param.PersonName))
            {
                query = query.Where(x => x.PersonName.Contains(param.PersonName));
            }

            if (!string.IsNullOrEmpty(param.InterviewPeople))
            {
                query = query.Where(x => x.InterviewPeople.Contains(param.InterviewPeople));
            }

            // 3. 计算总记录数
            var totalCount = await query.CountAsync();

            // 4. 执行分页查询
            var items = await query
                .OrderByDescending(x => x.InterviewTime)
                .Skip((param.PageIndex - 1) * param.PageSize)
                .Take(param.PageSize)
                .ToListAsync();

            // 5. 构建返回结果
            var result = new PagedResultDto<JobApplication>
            {
                TotalCount = totalCount,
                Items = items
            };

            return Json(new { 
                code = 0, 
                msg = "success", 
                count = result.TotalCount,
                data = result.Items
            });
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> ExportToExcel(string personName = "", string interviewPeople = "")
        {
            try
            {
                // 创建查询参数对象
                var input = new JobApplicationPageListDTO
                {
                    PersonName = personName,
                    InterviewPeople = interviewPeople
                };
                
                // 调用服务层方法导出Excel
                var excelBytes = await _jobApplicationService.ExportToExcelAsync(input);
                
                // 生成文件名
                string fileName = $"入职申请列表_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                
                // 返回Excel文件
                return File(excelBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, msg = "导出失败：" + ex.Message });
            }
        }
        /// <summary>
        /// 显示入职申请分页列表
        /// </summary>
        /// <param name="param">查询参数</param>
        /// <returns>分页结果</returns>
        [HttpGet]
        public async Task<IActionResult> JobReviewPageList([FromQuery] JobApplicationPageListDTO param)
        {
            // 1. 构建查询
            var query = await _jobApplicationRepository
                .GetQueryableAsync();

            // 2. 应用筛选条件
            if (!string.IsNullOrEmpty(param.PersonName))
            {
                query = query.Where(x => x.PersonName.Contains(param.PersonName));
            }

            if (!string.IsNullOrEmpty(param.InterviewPeople))
            {
                query = query.Where(x => x.InterviewPeople.Contains(param.InterviewPeople));
            }

            // 3. 计算总记录数
            var totalCount = await query.CountAsync();

            // 4. 执行分页查询
            var items = await query
                .OrderByDescending(x => x.InterviewTime)
                .Skip((param.PageIndex - 1) * param.PageSize)
                .Take(param.PageSize)
                .ToListAsync();

            // 5. 构建返回结果
            var result = new PagedResultDto<JobApplication>
            {
                TotalCount = totalCount,
                Items = items
            };

            return Json(new
            {
                code = 0,
                msg = "success",
                count = result.TotalCount,
                data = result.Items
            });
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> ExportReviewToExcel(string personName = "", string interviewPeople = "")
        {
            try
            {
                // 创建查询参数对象
                var input = new JobApplicationPageListDTO
                {
                    PersonName = personName,
                    InterviewPeople = interviewPeople
                };

                // 调用服务层方法导出Excel
                var excelBytes = await _jobApplicationService.ExportToExcelAsync(input);

                // 生成文件名
                string fileName = $"入职申请列表_{DateTime.Now:yyyyMMddHHmmss}.xlsx";

                // 返回Excel文件
                return File(excelBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, msg = "导出失败：" + ex.Message });
            }
        }
    }
}
